import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: AliceMana
 * Date: 2023-01-03
 * Time: 16:59
 */
// https://leetcode.cn/problems/find-words-that-can-be-formed-by-characters/
public class Solution {
    public static int countCharacters(String[] words, String chars) {
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < chars.length(); i++) {
            if (!map.containsKey(chars.charAt(i))) {
                map.put(chars.charAt(i), 1);
            } else {
                map.put(chars.charAt(i), map.get(chars.charAt(i))+1);
            }
        }
        int ret = 0;
        for (int i = 0; i < words.length; i++) {
            Map<Character, Integer> map1 = new HashMap<>(map);
            int count = 0;
            boolean flag = true;
            for (int j = 0; j < words[i].length(); j++) {
                if (map1.containsKey(words[i].charAt(j))) {
                    if (map1.get(words[i].charAt(j)) > 1) {
                        map1.put(words[i].charAt(j), map1.get(words[i].charAt(j))-1);
                        count++;
                    } else if (map1.get(words[i].charAt(j)) == 1) {
                        map1.remove(words[i].charAt(j));
                        count++;
                    }
                } else {
                    flag = false;
                }
            }
            if (flag) {
                ret += count;
            }
        }
        return ret;
    }
    public static void main(String[] args) {
        String[] words = {"hello","world","leetcode"};
        String chars = "welldonehoneyr";
        System.out.println(countCharacters(words, chars));
    }
}
